<?php

class MusiXMatchApi {
	
	private $api_key;
	private $url;
	
	private function __construct($key){
		$this->api_key= $key;
		$this->url = "http://api.musixmatch.com/ws/1.1/";	
	}
	
	public static function getInstance($key){
		return new self($key);
	}
	
	private function makeRequest($method,$methodParamArray = array() ){
		$paramArray = array("apikey" => $this->api_key, "format" => "xml");
		$paramArray =  array_merge($paramArray,$methodParamArray);
		$resultat = Outils_Connexion::curl_get($this->url.$method,$paramArray);
		return $this->getXMLResult($resultat);
	}
	
	private function getXMLResult($str){
		$xml =  simplexml_load_string($str);
		if ($xml->header->status_code == "200"){
			return $xml;
		} else {
			throw new Exception($xml->header->status_code." Artiste et/ou morceau inconnu");
		}
	}
	
	public function getLyrics($artist,$trackname){
			$xml = $this->makeRequest("track.search",array("q_artist" => $artist, "q_track" => $trackname, "page_size" =>"1", "f_has_lyrics"=>"1"));
			$id = (string) $xml->body->track_list->track->track_id;
			$xmlLyric = $this->makeRequest("track.lyrics.get",array("track_id" => $id));
			$lyric =  (string) $xmlLyric->body->lyrics->lyrics_body;
			$ligne = explode("\n",$lyric);
			$lyric_str = "";
			foreach ($ligne as $l){
				$lyric_str .= $l."<br/>";	
			}
			$lyric_str = substr($lyric_str,0,-5) . "...";
			$tracking_img_src = (string) $xmlLyric->body->lyrics->pixel_tracking_url;
			$html = "<p>{$lyric_str}</p><figure><img src=\"{$tracking_img_src}\" alt=\"Tracking MusiXMatch\"/></figure>";
			
			return $html;

	}
	
	
	
}


?>